package com.tron.dobest.netty.socket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame;
import io.netty.channel.ChannelHandler.Sharable;

/**
 * 描述：
 *
 * @author TRON
 * @since 2020-06-18
 */
@Sharable
public class BinaryWebSocketFrameHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {

    private ChannelGroup group;

    public BinaryWebSocketFrameHandler(ChannelGroup group) {
        this.group = group;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame binaryWebSocketFrame) throws Exception {
        boolean finalFragment = binaryWebSocketFrame.isFinalFragment();
        System.out.println("处理二进制数据" + binaryWebSocketFrame.content() + "是否为最终分片：" + finalFragment);
        if (!finalFragment) {
            System.out.println("把非终止分片数据交给下一个ContinuationWebSocketFrameHandler处理");
            ContinuationWebSocketFrame continuationWebSocketFrame = new ContinuationWebSocketFrame(false,0,binaryWebSocketFrame.content());
            //.retain增加使用计数，防止被释放。(SimpleChannelInboundHandler会自动释放资源)
            ctx.fireChannelRead(continuationWebSocketFrame.retain());
        }
    }
}
